#include "csvparser.hpp"
using namespace com::jimblogger;
csvparser::csvparser(){}
csvparser::~csvparser(){}

void csvparser::readCSV(std::string filename)
{
ifstream myfile (filename.data());
string line;
int linecount=0;

	while (getline( myfile, line ))
	{
 	

		 parseCSVLine(line);

 		
		linecount++;
	}
}

void csvparser::parseCSVLine(std::string line)
{
	size_t pos1=0,pos2=0,lastpos=0,ccount=0,tlength=0;
	int i=0; int x;
	lastpos = line.rfind(",");
	char * cstr;
	cstr = new char [line.size()+1];
	strcpy(cstr, line.c_str());
	while(cstr[i]!='\0'){ if(cstr[i] == ','){ ccount++;} i++;}//count how many commas there are. This should tell you how many fields there are.
	string csvData;
	csvrecord row = csvrecord(ccount+1);

	for(x=0; x < (ccount +1); x++)
	{
		if (pos1 ==0 )
		{
		pos1 = 0;
		pos2 = line.find(",", pos1);
		tlength = pos2 - pos1;
		csvData = line.substr(pos1,tlength);
		if (tlength==1 ){csvData="-";}

		pos1 = pos2+1;

		}else{
		pos2 = line.find(",", pos1+1);
		tlength = pos2 - pos1;
		csvData = line.substr(pos1,tlength);
		if (tlength==1){csvData="-";}
		
		pos1 = pos2+1;
		}

		 //add data to this record. csvData = one column of data from one row. We have to build a row this way.
		 row.addColumn(csvData,x);
 //cout << "xx" << endl;
		
	}
	
	addRow(row);//add the row to our collection of rows.
}

int csvparser::size()
{
return collection.size();
}

com::jimblogger::csvrecord csvparser::getRow(int it)
{
	return (csvrecord) collection[it];
}

void csvparser::addRow(com::jimblogger::csvrecord rec)
{
	int alm_count=0;
	int nextElement=0;
	alm_count = (int) collection.size();
	nextElement=alm_count+1;
	collection.push_back(rec);//add alarm to the internal alarm collection vector.
}


